package com.buildings.view;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.buildings.R;
import com.buildings.activity.table.CraterActivity;
import com.buildings.activity.table.DrillHoleActivity;
import com.buildings.activity.table.FaultSvyPointActivity;
import com.buildings.activity.table.GeoGeomorphySvyPointActivity;
import com.buildings.activity.table.GeochemicalSvyLineActivity;
import com.buildings.activity.table.GeochemicalSvyPointActivity;
import com.buildings.activity.table.GeologicalSvyLineActivity;
import com.buildings.activity.table.GeologicalSvyPlanningLineActivity;
import com.buildings.activity.table.GeologicalSvyPlanningPtActivity;
import com.buildings.activity.table.GeologicalSvyPointActivity;
import com.buildings.activity.table.GeomorStationActivity;
import com.buildings.activity.table.GeomorphySvyLineActivity;
import com.buildings.activity.table.GeomorphySvyPointActivity;
import com.buildings.activity.table.GeomorphySvyReProfActivity;
import com.buildings.activity.table.GeomorphySvyRegionActivity;
import com.buildings.activity.table.GeomorphySvySamplePointActivity;
import com.buildings.activity.table.GeophySvyLineActivity;
import com.buildings.activity.table.GeophySvyPointActivity;
import com.buildings.activity.table.LavaActivity;
import com.buildings.activity.table.SamplePointActivity;
import com.buildings.activity.table.StratigraphySvyPointActivity;
import com.buildings.activity.table.TanCaodianActivity;
import com.buildings.activity.table.VolcanicSamplePointActivity;
import com.buildings.activity.table.VolcanicSvyPointActivity;
import com.buildings.api.Api;
import com.buildings.bean.ProjectBean;
import com.buildings.bean.ProjectListBean;
import com.buildings.bean.TableTypeListBean;
import com.buildings.bean.TaskListNewBean;
import com.buildings.bean.TaskNewBean;
import com.buildings.event.AboutTaskEvent;
import com.buildings.event.EventCode;
import com.buildings.event.MessageEvent;
import com.buildings.event.MessageEventEntity;
import com.buildings.http.BaseCallBack;
import com.buildings.http.MyHttpClient;
import com.buildings.util.CustomToast;
import com.buildings.util.DataUtils;
import com.buildings.util.SPUtil;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class AboutTaskFragmentDialog extends DialogFragment implements View.OnClickListener {
    View mView;
    private Spinner sprinnerProject, sprinnerTask;
    private ArrayAdapter<String> sprinnerProjectAdapter;
    private ArrayAdapter<String> sprinnerTaskAdapter;
    private List<String> projectList = new ArrayList<>();
    private List<String> taskList = new ArrayList<>();
    private List<ProjectBean> datas = new ArrayList<>();
    private List<TaskNewBean> taskNewBeans = new ArrayList<>();
    private String projectId;
    private String taskId;
    private RelativeLayout rl_parent;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.custom_dialog);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        super.onActivityCreated(savedInstanceState);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0x00000000));
        getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.dialog_start_task, container, false);
        Window window = getDialog().getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        WindowManager.LayoutParams params = window.getAttributes();
        params.gravity = Gravity.BOTTOM;
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);
        init();
        return mView;
    }

    private TextView tvOver;
    private LinearLayout llProject, llTask, ll_table, ll_table_type;

    private void init() {
        sprinnerProject = mView.findViewById(R.id.sprinner_project);
        sprinnerTask = mView.findViewById(R.id.sprinner_task);
        llProject = mView.findViewById(R.id.ll_project);
        llTask = mView.findViewById(R.id.ll_task);
        tvOver = mView.findViewById(R.id.tv_over);
        ll_table_type = mView.findViewById(R.id.ll_table_type);
        ll_table = mView.findViewById(R.id.ll_table);
        rl_parent = mView.findViewById(R.id.rl_parent);
        rl_parent.setOnClickListener(this);
        tvOver.setOnClickListener(this);
        ll_table.setVisibility(View.GONE);
        ll_table_type.setVisibility(View.GONE);
        sprinnerProjectAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, projectList);
        sprinnerProject.setAdapter(sprinnerProjectAdapter);
        sprinnerProject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //记录项目id
                projectId = datas.get(position).getProjectId();
                //清空任务数据，重新获取，刷新任务适配器
                taskList.clear();
                if (null != sprinnerTaskAdapter) {
                    sprinnerTaskAdapter.notifyDataSetChanged();
                }
                httpTask();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sprinnerTaskAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, taskList);
        sprinnerTask.setAdapter(sprinnerTaskAdapter);
        sprinnerTask.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //记录任务id
                taskId = taskNewBeans.get(position).getTaskId();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        http();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_over:
                EventBus.getDefault().post(new AboutTaskEvent(1,projectId,taskId));
                dismiss();
                break;
            case R.id.rl_parent:
                dismiss();
                break;
        }
    }

    /**
     * isOnline 是否在线
     */
    public static AboutTaskFragmentDialog newInstance() {
        AboutTaskFragmentDialog fragmentB = new AboutTaskFragmentDialog();
        Bundle bundle = new Bundle();
        fragmentB.setArguments(bundle);
        return fragmentB;
    }

    private void http() {
        String url = Api.QUERY_HDD_PROJECT + "?curPage=1" + "&personId=" + SPUtil.get("userId", "") + "&pageSize=1000";
        MyHttpClient
                .newBuilder()
                .get()
                .url(url)
                .build()
                .enqueue(new BaseCallBack<ProjectListBean>() {
                    @Override
                    public void onSuccess(ProjectListBean bean) {
                        super.onSuccess(bean);
                        if (bean != null && bean.getCode() == 200) {
                            datas.clear();
                            List<ProjectBean> result = bean.getData().getRows();
                            datas.addAll(result);
                            //所想项目数据处理
                            if (datas.size() == 0) {
                                CustomToast.showToast(getActivity(), "暂无项目数据");
                                return;
                            }
                            for (ProjectBean projectBean : datas) {
                                projectList.add(projectBean.getProjectName());
                            }
                            //刷新适配器
                            if (null != sprinnerProjectAdapter) {
                                sprinnerProjectAdapter.notifyDataSetChanged();
                            }
                            //获取所属任务
                            httpTask();
                        } else {
                            CustomToast.showToast(getActivity(), "获取失败");
                        }
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CustomToast.showToast(getActivity(), "网络异常");
                            }
                        });
                    }
                });
    }


    private void httpTask() {
        if (TextUtils.isEmpty(projectId)) {
            return;
        }
        String url = Api.QUERY_HDD_TASK + "?curPage=1" + "&projectId=" + projectId + "&pageSize=1000";
        MyHttpClient
                .newBuilder()
                .get()
                .url(url)
                .build()
                .enqueue(new BaseCallBack<TaskListNewBean>() {
                    @Override
                    public void onSuccess(TaskListNewBean bean) {
                        super.onSuccess(bean);
                        if (bean != null && bean.getCode() == 200) {
                            List<TaskNewBean> result = bean.getData().getRows();
                            //设置默认值
                            if (result.size() != 0) {
                                taskNewBeans.clear();
                                taskId = result.get(0).getTaskId();
                                taskNewBeans.addAll(result);
                            }
                            taskList.clear();
                            //数据处理 刷新
                            for (TaskNewBean taskNewBean : taskNewBeans) {
                                taskList.add(taskNewBean.getTaskName());
                            }
                            if (sprinnerTaskAdapter != null) {
                                sprinnerTaskAdapter.notifyDataSetChanged();
                            }
                        } else {
                            CustomToast.showToast(getActivity(), "获取失败");
                        }
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CustomToast.showToast(getActivity(), "网络异常");
                            }
                        });
                    }
                });
    }
}
